# -*- coding: utf-8 -*-
import PySimpleGUI as sg
from PIL import Image, ImageFilter
from pathlib import Path
import os

def img2grey(imgFile):
    if imgFile.suffix.lower() == '.jpg' or imgFile.suffix.lower() == '.png':
        img = Image.open(imgFile)
        outImg = img.convert('L')
        oImg = outImg.filter(ImageFilter.SHARPEN)
        return oImg

def img2value(img, threshold):
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    return img.point(table, '1')

def run_window():
    label1_1 = sg.Text(" 源 文件夹")
    label1_2 = sg.Text("目标文件夹")
    srcdir = sg.InputText(size=(40,20))
    destdir = sg.InputText(size=(40,20))
    src_browser = sg.FolderBrowse('浏览', key='SrcDir')
    dest_browser = sg.FolderBrowse('浏览', key='DestDir')
    label2 = sg.Text('二值化阈值')
    slidbar = sg.Slider(range=(30, 230), default_value=100, orientation='h', size=(26, 20), key='slider')
    label3 = sg.Text("当前进度")
    progressbar = sg.ProgressBar(1000, orientation='h', size=(32, 20), key='progbar')
    ok_btn = sg.Button('确定')
    cancel_btn = sg.Button('退出')
    # 构造窗体
    layout = [[label1_1, srcdir, src_browser],
              [label1_2, destdir, dest_browser],
              [label2, slidbar],
              [label3, progressbar], [ok_btn, cancel_btn]]
    window = sg.Window('作业图片批量转换', layout)

    # Create the event loop
    while True:
        event, values = window.read(timeout=100)
        if event in (None, '退出'):
            # User closed the Window or hit the Cancel button
            break
        if event == sg.TIMEOUT_KEY:
            # print('Nothing happened')
            pass
        elif event == '确定' and values['SrcDir'] and values['DestDir']:
            window.Element('progbar').UpdateBar(0)
            srcDir = values['SrcDir']
            destDir = values['DestDir']
            files = Path(srcDir).iterdir()
            totalFiles = len(os.listdir(srcDir))
            finishFiles = 0
            for file in files:
                if file.is_file():
                    img = img2value(img2grey(file), int(values['slider']))
                    outFile = Path('/').joinpath(destDir, file.stem + '_1' + file.suffix)
                    img.save(outFile)
                finishFiles += 1
                window.Element('progbar').UpdateBar(int(finishFiles*1000/totalFiles))
            sg.popup_ok('转换工作完成!')
        else:
            # print(values['slider'])
            sg.popup_ok('请选择要转换的图片源文件夹以及生成图片的目标文件夹!')

    window.close()

if __name__ == '__main__':
    run_window()
